<template>
  <div class="add_task">
    <el-title :title="title"></el-title>
    <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <!-- <el-form-item label="协同治理事项名称:" prop="username">
            <el-input type="text" v-model="ruleForm.username" autocomplete="off"></el-input>
        </el-form-item> -->
      <div>
        <el-form-item label="呼叫单位:" prop="company" v-if="power">
          <el-select v-model="ruleForm.company" multiple filterable placeholder="请选择">
            <el-option v-for="item in options" :key="item.value" :label="item.realname" :value="item.userid"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系号码:" prop="phone">
          <el-input v-model.number="ruleForm.phone"></el-input>
        </el-form-item>
      </div>
      <div>
        <el-form-item label="事项类别:" prop="username" v-if="power" >
          <el-select v-model="ruleForm.username" filterable placeholder="请选择" @change="nowList()">
            <el-option v-for="item in danList" :key="item.value" :label="item.class_name" :value="item.class_id"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="事项名称:" prop="type" v-if="power">
          <el-select v-model="ruleForm.type" filterable placeholder="请选择">
            <el-option v-for="item in optionsd" :key="item.value" :label="item.name" :value="item.id"> </el-option>
          </el-select>
        </el-form-item>
        <el-button type="primary" style="margin-left:20px;" @click="open">实施依据</el-button>
      </div>
      <!-- <el-form-item label="计划日期:" prop="date" v-if="power">
            <el-date-picker
                v-model="ruleForm.date"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
            </el-date-picker>
        </el-form-item> -->
      <el-form-item label="具体情形:" prop="statement" class="explain">
        <el-input type="textarea" v-model="ruleForm.explain"></el-input>
      </el-form-item>
      <el-form-item label="上传图片:" class="uppic">
        <el-upload
          ref="pictureUpload"
          action="/api/project/upload"
          list-type="picture-card"
          :on-success="handlePreview"
          :on-error="handleError"
          :on-remove="handleRemove"
          :before-upload="beforeUpload"
          multiple
        >
          <i slot="default" class="el-icon-plus"></i>
          <div slot="file" slot-scope="{ file }">
            <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
            <span class="el-upload-list__item-actions">
              <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                <i class="el-icon-zoom-in"></i>
              </span>
              <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
                <i class="el-icon-delete"></i>
              </span>
            </span>
          </div>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>

      <el-form-item label="上传视频:" class="uppic">
        <el-upload
          class="upload-demo"
          drag
          action="/api/project/upload?type=102"
          :on-success="handleVideoSuccess"
          :show-file-list="false"
          :disabled="videoDis"
          multiple
        >
          <span v-if="videoForm.showVideoPath != '' && !videoFlag" class="eldelete" @click="videoRemove">
            <i class="el-icon-delete"></i>
          </span>
          <video
            v-if="videoForm.showVideoPath != '' && !videoFlag"
            :src="videoForm.showVideoPath"
            class="avatar video-avatar"
            controls="controls"
          ></video>
          <i v-else-if="videoForm.showVideoPath == '' && !videoFlag" class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        </el-upload>
      </el-form-item>
      <el-form-item label="上传附件:" class="uppic">
        <el-upload
          class="upload-demo upload_appen"
          action="/api/project/upload?type=103"
          :on-success="handleAppenPreview"
          :on-remove="handleAppenRemove"
          multiple
        >
          <el-button size="small" type="primary">点击上传</el-button>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import elTitle from '@/components/title'
import { uploadRemove, addTask, userUnit, apiassociat, projectmain, projectvarAdd, editTask, userInfo } from '@/utils/index.js'
export default {
  data() {
    var username = (rule, value, callback) => {
      if (value === '') {
        this.$message.closeAll()
        this.$message.warning('项目名称不能为空')
        callback(new Error(' '))
      } else {
        callback()
      }
    }
    var type = (rule, value, callback) => {
      if (value === '') {
        this.$message.closeAll()
        this.$message.warning('任务类型不能为空')
        callback(new Error(' '))
      } else {
        callback()
      }
    }
    var date = (rule, value, callback) => {
      if (value === '') {
        this.$message.closeAll()
        this.$message.warning('计划日期不能为空')
        callback(new Error(' '))
      } else {
        callback()
      }
    }
    var company = (rule, value, callback) => {
      if (value === '') {
        this.$message.closeAll()
        this.$message.warning('选择单位不能为空')
        callback(new Error(' '))
      } else {
        callback()
      }
    }
    var explain = (rule, value, callback) => {
      if (value === '') {
        this.$message.closeAll()
        this.$message.warning('任务说明不能为空')
        callback(new Error(' '))
      } else {
        callback()
      }
    }
    var phone = (rule, value, callback) => {
      if (value === '') {
        this.$message.closeAll()
        this.$message.warning('联系电话不能为空')
        callback(new Error(' '))
      } else {
        callback()
      }
    }
    return {
      // 上传视频
      videoFlag: false,
      //是否显示进度条
      videoUploadPercent: '',
      //进度条的进度，
      isShowUploadVideo: false,
      //显示上传按钮
      videoForm: {
        showVideoPath: '',
        id: '',
      },
      // 结束上传
      videoDis: false,
      title: '创建任务',
      ruleForm: {
        username: '',
        type: '',
        phone: '',
        date: '',
        company: '',
        explain: '',
      },
      rules: {
        username: [{ validator: username, trigger: 'blur' }],
        type: [{ validator: type, trigger: 'blur' }],
        date: [{ validator: date, trigger: 'blur' }],
        company: [{ validator: company, trigger: 'blur' }],
        explain: [{ validator: explain, trigger: 'blur' }],
        phone: [{ validator: phone, trigger: 'blur' }],
      },
      optionsd: [],
      options: [],
      // 上传图片
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      file: [],
      danList: [],
      power: true,
    }
  },
  components: {
    elTitle,
  },
  beforeCreate() {
    userInfo().then((res) => {
      if (res.code != '0') {
        this.$message.closeAll()
        this.$message.warning(res.msg)
        this.$router.push('/')
      } else {
        if (res.data.member == 0) {
          this.power = false
          this.title = '提交任务'
        }
      }
    })
  },
  created() {
    // 获取事项
    apiassociat({
      class_id: '11',
    }).then((res) => {
      console.log(res)
      this.optionsd = res.data
    })
    // 获取单位
    userUnit().then((res) => {
      console.log(res)
      this.options = res.data
    })
    // 事项类别
    projectmain().then((res) => {
      console.log(res)
      this.danList = res.data
    })
  },
  methods: {
    nowList() {
      apiassociat({
        class_id: this.ruleForm.username,
      }).then((res) => {
        console.log(res)
        this.optionsd = res.data
        this.ruleForm.type = ''
      })
    },
     open() {
        let msg
        for(let x=0;x<this.optionsd.length;x++){
            if(this.optionsd[x].id==this.ruleForm.type){
                msg=this.optionsd[x].content
            }
        }
        if(!msg) return
        this.$alert(msg, '事件名称', {
          confirmButtonText: '确定',
        });
      },
    //上传成功回调
    handleVideoSuccess(res) {
      this.isShowUploadVideo = true
      this.videoFlag = false
      this.videoUploadPercent = 0
      console.log(res)
      //后台上传地址
      if (res.code == 0) {
        this.videoForm.id = res.data.id
        this.videoForm.showVideoPath = res.data.src
        this.file.push(res.data)
        this.videoDis = true
      }
    },
    // 上传图片
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 上传成功
    handlePreview(file) {
      console.log(file)
      this.file.push(file.data)
      console.log(this.file)
      this.$message.closeAll()
      this.$message.success('上传成功')
    },
    // 失败
    handleError(file) {
      console.log(file)
    },
    // 移除视频
    videoRemove() {
      console.log(this.videoForm.id)
      uploadRemove({
        id: this.videoForm.id,
      }).then((res) => {
        if (res.code == '0') {
          // 1.从pics数组中，找到图片对应的索引值
          let j = this.file.findIndex((x) => x.id == this.videoForm.id)
          // 2.调用splice方法，移除图片信息
          this.file.splice(j, 1)
          console.log(this.file)

          this.videoForm.showVideoPath = ''
          this.videoForm.id = ''
          this.videoDis = false
          console.log(this.videoForm)
          this.$message.closeAll()
          this.$message.success(res.msg)
        } else {
          this.$message.closeAll()
          this.$message.warning(res.msg)
        }
      })
    },
    // 移除图片
    handleRemove(file) {
      uploadRemove({
        id: file.response.data.id,
      }).then((res) => {
        if (res.code == '0') {
          // 移除file中数据
          // 1.从pics数组中，找到图片对应的索引值
          let j = this.file.findIndex((x) => x.id == file.response.data.id)
          // 2.调用splice方法，移除图片信息
          this.file.splice(j, 1)
          console.log(this.file)
          // 删除预览图片
          let uploadFiles = this.$refs.pictureUpload.uploadFiles
          for (var i = 0; i < uploadFiles.length; i++) {
            if (uploadFiles[i]['url'] == file.url) {
              uploadFiles.splice(i, 1)
            }
          }
          this.$message.closeAll()
          this.$message.success(res.msg)
        } else {
          this.$message.closeAll()
          this.$message.warning(res.msg)
        }
      })
    },
    beforeUpload(file) {
      console.log(file)
    },
    //上传图片end
    // 上传附件
    handleAppenPreview(file) {
      console.log(file)
      this.file.push(file.data)
      console.log(this.file)
      this.$message.closeAll()
      this.$message.success('上传成功')
    },
    handleAppenRemove(file) {
      console.log(file)
      uploadRemove({
        id: file.response.data.id,
      }).then((res) => {
        if (res.code == '0') {
          // 移除file中数据
          // 1.从pics数组中，找到图片对应的索引值
          let j = this.file.findIndex((x) => x.id == file.response.data.id)
          // 2.调用splice方法，移除图片信息
          this.file.splice(j, 1)
          console.log(this.file)
          this.$message.closeAll()
          this.$message.success(res.msg)
        } else {
          this.$message.closeAll()
          this.$message.warning(res.msg)
        }
      })
    },

    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.$store.state.userInfo.member == 0) {
            projectvarAdd({
              phone: this.ruleForm.phone,
              explain: this.ruleForm.explain,
              file: this.file,
            }).then((res) => {
              console.log(res)
              if (res.code == '0') {
                this.$message.closeAll()
                this.$message.success('提交成功')
                setTimeout(() => {
                  this.$router.push('/my_task')
                }, 800)
              } else {
                this.$message.closeAll()
                this.$message.warning(res.msg)
              }
            })
          } else {
            if (this.$route.query.rowId != undefined) {
              editTask({
                id: this.$route.query.rowId,
                name: this.ruleForm.username,
                genre: this.ruleForm.type,
                stime: this.ruleForm.date[0],
                etime: this.ruleForm.date[1],
                cate_id: this.ruleForm.company,
                phone: this.ruleForm.phone,
                explain: this.ruleForm.explain,
                file: this.file,
              }).then((res) => {
                console.log(res)
                if (res.code == '0') {
                  this.$message.closeAll()
                  this.$message.success('创建任务')
                  setTimeout(() => {
                    this.$router.push('/my_task')
                  }, 800)
                } else {
                  this.$message.closeAll()
                  this.$message.warning(res.msg)
                }
              })
            } else {
              addTask({
                name: this.ruleForm.username,
                genre: this.ruleForm.type,
                stime: this.ruleForm.date[0],
                etime: this.ruleForm.date[1],
                cate_id: this.ruleForm.company,
                phone: this.ruleForm.phone,
                explain: this.ruleForm.explain,
                file: this.file,
              }).then((res) => {
                console.log(res)
                if (res.code == '0') {
                  this.$message.closeAll()
                  this.$message.success('创建任务')
                  setTimeout(() => {
                    this.$router.push('/my_task')
                  }, 800)
                } else {
                  this.$message.closeAll()
                  this.$message.warning(res.msg)
                }
              })
            }
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.add_task {
  background: #ffffff;
}
.el-select-dropdown__item {
  width: 370px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.demo-ruleForm::v-deep {
  margin-top: 15px;
  padding: 50px 30px !important;
  background-color: white;
  padding: 40px 0;
  max-width: 1200px;
  .el-form-item {
    display: inline-block;
    width: 500px;
    margin-bottom: 30px;
  }
  .el-form-item__label {
    width: 130px !important;
  }
  .el-form-item__content {
    margin-left: 130px !important;
  }
  .uppic {
    display: block;
    width: 100%;
    .el-upload-list__item {
      div {
        height: 146px;
      }
    }
  }
  .el-select {
    width: 100%;
  }
  .explain {
    display: block;
    width: 92%;
    .el-textarea__inner {
      height: 120px;
    }
  }
}
video {
  height: 100%;
}
.eldelete {
  position: absolute;
  right: 14px;
  font-size: 18px;
  color: #333;
}
.eldelete:hover {
  color: red;
}
.upload_appen {
  .el-upload-list__item {
    width: 50%;
  }
}
</style>


